package com.java46.service;

import com.java46.bean.Personnel;
import com.java46.exception.MyException;
import com.java46.mapper.PersonnelMapper;
import com.java46.util.ServiceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.naming.InsufficientResourcesException;
import java.util.List;

@Transactional
@Service
public class PersonnelService {

    //从spring得mapper接口
    @Autowired
    private PersonnelMapper personnelMapper;

    /**
     * 查询所有员工信息
     * @return 返回一个集合
     * @throws MyException
     */
    public List<Personnel> queryAllPersonnel() throws MyException {

        List<Personnel> personnels;
        personnels = personnelMapper.selectAll();
        ServiceUtil.checkListNull(personnels,"没有查询到员工数据！");

        return personnels;
    }

    /**
     * 根据员工编号查询员工信息
     * @param personnelId 员工编号
     * @return 返回员工对象
     * @throws MyException
     */
    public Personnel queryByPersonnelId(Integer personnelId) throws MyException {

        ServiceUtil.checkNull(personnelId,"员工编号不能为空！");
        Personnel personnel ;
        try {
            personnel = personnelMapper.selectByPrimaryKey(personnelId);
        }catch (Exception e){
            e.printStackTrace();
            throw new MyException("数据异常！");
        }
        ServiceUtil.checkNull(personnel,"根据员工编号查询员工失败！");

        return personnel;
    }

    /**
     * 添加员工
     * @param personnel 员工对象
     */
    public Integer addPersonnel(Personnel personnel) throws MyException {

        ServiceUtil.checkNull(personnel,"员工不能为空！");
        Integer result ;
        try {
            result = personnelMapper.insert(personnel);
        }catch (Exception e){
            e.printStackTrace();
            throw new MyException("数据异常！");
        }
        ServiceUtil.checkNull(result,"员工信息添加失败！");

        return result;
    }

    /**
     * 根据员工编号删除员工信息
     * @param personnelId 员工编号
     */
    public Integer deletePersonnel(Integer personnelId) throws MyException {

        ServiceUtil.checkNull(personnelId,"员工编号不能为空！");
        Integer result ;
        try {
            result = personnelMapper.deleteByPrimaryKey(personnelId);
        }catch (Exception e){
            e.printStackTrace();
            throw new MyException("数据异常！");
        }
        ServiceUtil.checkNull(result,"没有此员工编号，删除失败！");

        return result;
    }

    /**
     * 修改员工信息
     * @param personnel 员工对象
     */
    public Integer updatePersonnel(Personnel personnel) throws MyException {

        ServiceUtil.checkNull(personnel,"员工不能为空！");
        Integer result ;
        try {
            result = personnelMapper.updateByPrimaryKey(personnel);
        }catch (Exception e){
            e.printStackTrace();
            throw new MyException("数据异常！");
        }
        ServiceUtil.checkNull(result,"员工信息修改失败！");

        return result;
    }
}

